import {debounce, DebounceSettings} from 'lodash'
import {useRef} from 'react'
import useCreation from './useCreation'
// DebounceSettings：_.debounce第三个参数options对象类型
// debounce 创建一个 debounced（防抖动）函数


// _.debounce第三个参数options
// interface DebounceOptions {
//   maxWait?: number // 允许被延迟的最大值
//   leading?: boolean // 在延迟开始前调用，头部防抖
//   trailing?: boolean // 在延迟结束后调用，尾部防抖
// }
function useDebounceFn<T extends (...args: any) => any>(
    fn: T,
    options?: DebounceSettings,
) {
    const fnRef = useRef<T>(fn);
    const wait = options?.maxWait ? options?.maxWait : 1000;
    const debounced = useCreation(
        () =>
            debounce<T>(
                ((...args: any) => {
                    return fnRef.current(...args)
                }) as T,
                wait,
                options,
            ),
        [],
    );
    return {
        run: (debounced as unknown) as T,
        cancel: debounced.cancel, // 取消延迟的函数调用
        flush: debounced.flush, // 立即调用
    }
}

export default useDebounceFn;
